<?php
define('DS', DIRECTORY_SEPARATOR);
define('EXT', '.php');
define('HAMSTER_PATH', realpath(dirname(__FILE__)) . DS);

function launch($app_path = '') {
    define('APP_PATH', realpath($app_path) . DS);

    require HAMSTER_PATH . 'config' . EXT;
    require HAMSTER_PATH . 'controller' . EXT;
    require HAMSTER_PATH . 'view' . EXT;

    Config::getInstance()->init(file_exists($app_path . '/config.php')
        ? array_merge(include APP_PATH . 'config' . EXT, include HAMSTER_PATH . 'convention' . EXT)
        : include HAMSTER_PATH . 'convention' . EXT);

    $request = isset($_SERVER['PATH_INFO'])
        ? $_SERVER['PATH_INFO']
        : (isset($_SERVER['ORIG_PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : '/');

    if (!$segments = parse_route($request)) {
        $segments = parse_request($request);
    }

    dispatch($segments['controller'], $segments['action']);
}

function dispatch($controller = '', $action = '') {
    $controller_file = APP_PATH . 'controller' . DS . $controller . EXT;
    if (file_exists($controller_file)) {
        include $controller_file;
    }

    $class = ucfirst($controller) . 'Controller';
    $obj = new $class;
    call_user_func(array($obj, $action));
}

function parse_route($request = '') {
    return false;
}

function parse_request($request = '') {
    $request = ($trimmed_request = trim($request, '/')) ? explode('/', $trimmed_request) : null;
    $segments = array();
    $segments['controller'] = isset($request[0]) ? array_shift($request) : Config::getInstance()->get('default_controller');
    $segments['action'] = isset($request[0]) ? array_shift($request) : Config::getInstance()->get('default_action');
    for ($i = 0; $i < count($request); $i += 2) {
        $_GET[$request[$i]] = isset($request[$i+1]) ? $request[$i+1] : null;
    }
    return $segments;
}

function url_for() {
}

function dump($var = null) {
    ob_start();
    var_dump($var);
    $output = ob_get_clean();
    echo '<pre>';
    echo htmlspecialchars($output);
    echo '</pre>';
}
